package com.hcloud.uploadsdk;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cloud.wolibrary.WoLib;
import com.cloud.wolibrary.callback.ICreateTaskCallback;
import com.cloud.wolibrary.callback.IUploadResultCallback;
import com.cloud.wolibrary.manager.UploadManager;
import com.cloud.wolibrary.request.PutUploadRequest;
import com.cloud.wolibrary.request.ResumeUploadRequest;
import com.cloud.wolibrary.request.UploadRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class UploadActivity extends AppCompatActivity {


    private List<Upload> uploadList = new ArrayList();

    private UploadManager manager;

    private UploadAdapter uploadAdapter;

    private ProgressDialog progressDialog;

    private MyUploadStrategy myUploadStrategy;

    public long startTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_upload);

        findViewById(R.id.fl_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                startActivityForResult(intent, 1000);
            }
        });


        progressDialog = new ProgressDialog(this);
        uploadAdapter = new UploadAdapter();

        RecyclerView rv = findViewById(R.id.rv);

        rv.setLayoutManager(new LinearLayoutManager(this));

        rv.setAdapter(uploadAdapter);


        manager = new UploadManager();
        myUploadStrategy = new MyUploadStrategy();
        WoLib.getInstance().setUploadStrategy(myUploadStrategy);

        uploadAdapter.setData(uploadList);
        uploadAdapter.setManager(manager);
        uploadAdapter.setAc(this);

        findViewById(R.id.bt_all_pause).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog.show();
                for (Upload upload : uploadList) {
                    upload.getUploadRequest().setUploadStatus(2);
                    upload.cancel();
                }
                progressDialog.hide();
            }
        });

        findViewById(R.id.bt_all_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog.show();
                for (Upload upload : uploadList) {
                    upload.cancel();
                    //0 等待 1 上传中 2 暂停 3 上传成功 4 上传失败
                    if (manager != null && upload.getUploadRequest().getUploadStatus() != 3) {
                        upload.getUploadRequest().setUploadStatus(0);
                        manager.upload(upload.getUploadRequest());
                    }
                }
                progressDialog.hide();
            }
        });

        findViewById(R.id.bt_all_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog.hide();
                for (Upload upload : uploadList) {
                    upload.cancel();
                }
                uploadList.clear();
                uploadAdapter.setData(uploadList);
                progressDialog.hide();

                if (null != myUploadStrategy){
                    myUploadStrategy.getFilterUploadList().clear();
                }
            }
        });

        findViewById(R.id.bt_filter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != myUploadStrategy){
                    StringBuffer buffer = new StringBuffer();
                    List<File> fileList = myUploadStrategy.getFilterUploadList();
                    for (File file: fileList){
                        buffer.append(file.getName()).append("\n");
                    }
                    if (buffer.length() != 0){
                        ToastUtils.showShort(buffer.toString());
                    }
                }
            }
        });


//        ResumeUploadRequest resumeUploadRequest = new ResumeUploadRequest("1606130126080656196239173345", "/sdcard/hcloud_data/photo_movie/影集/影集202008051645.mp4");
//        manager.upload(resumeUploadRequest, new ICreateTaskCallback<UploadRequest>() {
//            @Override
//            public void createTaskSuccess(UploadRequest request, String uploadId) {
//                Log.d("woLib", "createTaskSuccess " + uploadId);
//            }
//
//            @Override
//            public void createTaskError(UploadRequest request, String code, String msg) {
//                Log.d("woLib", "createTaskError " + msg);
//            }
//        });
//
//        resumeUploadRequest.setUploadResultCallback(new IUploadResultCallback<UploadRequest>() {
//            @Override
//            public void uploadProgress(UploadRequest uploadRequest, UploadProgress uploadProgress) {
//                Log.d("woLib", "uploadProgress " + uploadProgress.getProgress());
//            }
//
//            @Override
//            public void uploadSuccess(UploadRequest uploadRequest, UploadProgress uploadProgress, String s) {
//                Log.d("woLib", "uploadSuccess " + s);
//            }
//
//            @Override
//            public void uploadError(UploadRequest uploadRequest, String s, String s1) {
//
//            }
//        });


//        String aa = AESBase64Util.encrypt("{\"cellphone\":\"15767971263\",\"fileHash\":\"149463\",\"fileLastmod\":\"1602579470000\",\"fileName\":\"lastPic.png\",\"fileSize\":\"149463\",\"fileType\":\"1\",\"partSize\":\"8388608\"}");
//        String aa = AESBase64Util.encrypt("LFtUagTLlDrgfBLCwO7kz1QcsvBsO9di5Rfa7o74DiXLfH9xcQYPxxPoPEO45Aac/c9Y3bRhkkQ9\\nViVKRGbp0iteKE/aUIzSoxsBvgnGMzNdtGl8zcv3Nu6cOGf2pRUBBQ9BcqcApAnowi8HSrALsn2a\\nG2cVOaeem2hpDK3XJVq1H0HiTsoJwoTUrwsEbUAZIot6qYAoVJDiSThYZiB8foIsAOgFudJKH536\\njHFfCMulbQFH3/hV9+Iii3DhxL2qb198dUBKZie8FXkGqailGfDGltYbbY3f4wom/WuBqqQ\\u003d\\n");
//        String aa = AESBase64Util.encrypt("abcdefg{:=}");
//        String result = "LFtUagTLlDrgfBLCwO7kz1QcsvBsO9di5Rfa7o74DiXLfH9xcQYPxxPoPEO45Aac/c9Y3bRhkkQ9\\nViVKRGbp0iteKE/aUIzSoxsBvgnGMzNdtGl8zcv3Nu6cOGf2pRUBBQ9BcqcApAnowi8HSrALsn2a\\nG2cVOaeem2hpDK3XJVq1H0HiTsoJwoTUrwsEbUAZIot6qYAoVJDiSThYZiB8foIsAOgFudJKH536\\njHFfCMulbQFH3/hV9+Iii3DhxL2qb198dUBKZie8FXkGqailGfDGltYbbY3f4wom/WuBqqQ\\u003d\\n";
        String result = "MmmanqK+KOMmfeoVS8l/kn5HhOsyhwCvVHTteEG5Fr5YSUkNAB7iI9sGxQSZhLkt";
//        String ccc= Base64.decode(result,Base64.DEFAULT);
        String bb = AESBase64Util.decrypt(result);
//        WoUtils.d(bb);
//        WoUtils.d(bb);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            if (data.getData() != null) {
                Uri uri = data.getData();
                String filePath = uri.toString();

                List<String> pathList = new ArrayList();
                pathList.add(filePath);
                uploadFile(pathList);
            } else {
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    List<String> pathList = new ArrayList();
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        Uri uri = item.getUri();
                        Log.d("YiLog", "uri:" + uri.toString());
                        String filePath = uri.toString();
                        pathList.add(filePath);
                    }
                    uploadFile(pathList);
                }
            }
        }
    }

    public void uploadFile(List<String> filePathList) {
        for (String filePath : filePathList) {
            startTime = System.currentTimeMillis();
            System.out.println("-----startTime: " + startTime);
            PutUploadRequest putRequest = new PutUploadRequest("13342888433",filePath);
            manager.upload(putRequest, new ICreateTaskCallback() {
                @Override
                public void createTaskSuccess(UploadRequest task, String uploadId) {
                }

                @Override
                public void createTaskError(UploadRequest task, String code, String msg) {
                    LogUtils.i("---createTaskError----" + code + "  " + msg);
                }
            });
            Upload upload = new Upload(filePath, putRequest);
            uploadList.add(upload);
        }
        uploadAdapter.setData(uploadList);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        for (Upload upload : uploadList) {
            upload.cancel();
        }
    }
}
